package com.sdkx.wear_os.retrofit.interceptor

import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import com.sdkx.wear_os.utils.ToastLogUtils.logUtil
import okhttp3.logging.HttpLoggingInterceptor

/**
 * 拦截器
 */
object InterceptorUtils {

    fun logInterceptor(): HttpLoggingInterceptor =
        HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            private val mMessage = StringBuilder()
            private var message = ""
            override fun log(message: String) {
                if (this.message.startsWith("--> GET") || this.message.startsWith("--> POST")) {
                    mMessage.setLength(0)
                }
                this.message = message
                try {
                    // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
                    if (this.message.startsWith("{") && this.message.endsWith("}") ||
                        this.message.startsWith("[") && this.message.endsWith("]")
                    ) {
                        val gson = GsonBuilder().setPrettyPrinting().create()
                        val jp = JsonParser.parseString(this.message)
                        this.message = gson.toJson(jp)
                    }
                    mMessage.append(this.message + "\n")
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                // 响应结束，打印整条日志
                if (this.message.startsWith("<-- END HTTP")) {
                    logUtil("message", "$mMessage\n=========================================")
                }
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY)//设置打印数据的级别
}

